while Loop

The structure of a while loop:

    initialize condition variable(s)
    while condition
        do these statements  % body of while loop
        update condition variable(s)
    end

where condition is a boolean expression comparing the condition variables.

control flow diagram of a while loop

The way a while loop works is as follows:

  1. The variables tested in the condition are assigned their initial values.
  2. The condition expression is evaluated.
  3. If the condition evaluates to true, then the statements in the body of the while loop are executed. The body of the loop must also include a way for the values of the condition variables to be updated, or an infinite loop will result.
  4. After the body of the while loop has finished executing, control goes back to the top of the while loop.
  5. This process repeats until the condition expression evaluates to false.
  6. If the condition evaluates to false, the statements in the body of the while loop are skipped and control continues at the next statement after the while loop.

As in the if statement, the while statement uses end to indicate the end of the loop.